<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>ES5构造函数</title>
</head>
<body>
  <script>
    /**
     * ES5的原型
    */
    // bad
    function User (name, age) {
      this.name = name;
      this.age = age;
      // 这里因为每次实例化时都会重新创建一个同样的函数，会占用内存，引起内存泄露。
      this.info = function () {
        console.log(`${this.name} and ${this.age}`);
      }
    }
    const user1 = new User('user1', 18);
    const user2 = new User('user2', 20);
    console.log('user1', user1.info());
    console.log('user2', user2.info());


    // good
    function Teacher (name, age) {
      this.name = name;
      this.age = age;
    }
    // 这样将函数挂载到Teacher的原型对象上，可以减少内存开销
    Teacher.prototype.info = function () {
      console.log(`${this.name} and ${this.age}`);
    }
    const teacher1 = new Teacher('teacher1', 24);
    const teacher2 = new Teacher('teacher2', 29);
    // 还可以对原型对象上的方法或者属性进行重写
    Teacher.prototype.info = function () {
      console.log('i am teacher');
    }
    console.log(teacher1.info());
    console.log(teacher2.info());
  </script>
</body>
</html>